package com.me.template4j.util.encrypt;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;
import javax.crypto.Cipher;
import java.util.Base64;


public class AESEncrypt implements Encrypt {

    /**
     * 加解密统一编码方式
     */
    private final static String ENCODING = "utf-8";

    /**
     * 加解密方式
     */
    private final static String ALGORITHM = "AES";

    /**
     * 加密模式及填充方式
     */
    private final static String PATTERN = "AES/ECB/pkcs5padding";

    /**
     * 秘钥生成来源
     */
    public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String mySalt = "template4j123456";

    /**
     * 生成AES密钥对象
     *
     */

    @Override
    public String encoded(String str) {
        try {
            SecretKey secretKey = new SecretKeySpec(mySalt.getBytes(ENCODING), ALGORITHM);
            // AES加密采用pkcs5padding填充
            Cipher cipher = Cipher.getInstance(PATTERN);
            //用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            //执行加密操作
            byte[] encryptData = cipher.doFinal(str.getBytes(ENCODING));
            return Base64.getEncoder().encodeToString(encryptData);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String decoded(String str) {
        try {
            SecretKey secretKey = new SecretKeySpec(mySalt.getBytes(ENCODING), ALGORITHM);
            // 获取 AES 密码器
            Cipher cipher = Cipher.getInstance(PATTERN);
            // 初始化密码器（解密模型）
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            // 解密数据, 返回明文
            byte[] encryptData = cipher.doFinal(Base64.getDecoder().decode(str));
            return new String(encryptData, ENCODING);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean compare(String psw1, String psw2) {
        String decoded1 = this.decoded(psw1);
        String decoded2 = psw2;
        return decoded1.equals(decoded2);
    }

}
